﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XbdSoft.Contract;
using XbdSoft.Domain;
using System.Configuration;
using System.Net;

namespace XbdSoft.Services
{
    public class AccountService:IAccountService
    {
        private const string ForgotPasswordUrlKey = "forgotPasswordUrl";
        private const string RegisterUrlKey = "registerUrl";
        private const string MD5UrlKey = "md5Url";

        #region IAccountService Members

        public string GetForgotPasswordUrl()
        {
            return ConfigurationManager.AppSettings[ForgotPasswordUrlKey] ?? "http://www.xbd61.com/";
        }

        public string GetRegisterUrl()
        {
            return ConfigurationManager.AppSettings[RegisterUrlKey] ?? "http://www.xbd61.com/";
        }

        public bool Login(string userName, string password)
        {
            using (var context = new XbdDbContext(Constants.LoginConnectionString))
            {
                return context.Users.Any(u => u.Password.Equals(password) && u.UserName.Equals(userName));
            }
        }

        public string EncryptByMD5(string text)
        {
            var result = text;
            try
            {
                var url = string.Format(ConfigurationManager.AppSettings[MD5UrlKey], text);
                var webRequest = WebRequest.Create(url);
                using (var response = webRequest.GetResponse()) 
                using (var stream = response.GetResponseStream())
                {
                    var length = response.ContentLength;
                    var buffer = new byte[length];
                    stream.Read(buffer, 0, (int)length);
                    result = System.Text.Encoding.UTF8.GetString(buffer);
                } 
            }
            catch { }
            return result;
        }
        #endregion
    }
}
